package com.example.petchating.screens

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.viewport.ScreenViewport
import com.example.petchating.Main
import com.example.petchating.UI.ButtonGroup
import com.example.petchating.camera.CameraController
import com.example.petchating.collision.CollisionManager
import com.example.petchating.entities.Pet
import com.example.petchating.map.MapLoader
import com.example.petchating.map.MapRenderer
import ktx.app.KtxScreen
import com.example.petchating.network.ChatHistoryRepository
import com.example.petchating.network.ChatService
import com.example.petchating.network.EmotionService
import com.example.petchating.UI.ChatDialog

class GameScreen(
    private val game: Main,
    private val chatService: ChatService,
    private val historyRepo: ChatHistoryRepository,
    private val analyzeEmotionService: EmotionService
) : KtxScreen {
    //屏幕高宽
    private val screenWidth = Gdx.graphics.width
    private val screenHeight = Gdx.graphics.height
    //地图、宠物、摄影机
    private lateinit var mapLoader : MapLoader
    private lateinit var pet: Pet
    private lateinit var cameraController : CameraController
    private lateinit var mapRenderer : MapRenderer
    //screenViewport：UI视口
    private val screenViewport: ScreenViewport = ScreenViewport()
    //渲染绘制实例
    private lateinit var batch: SpriteBatch
    //按钮布相关
    private lateinit var buttonGroup: ButtonGroup
    private val touchPos = Vector2()
    //碰撞管理器
    private lateinit var collisionManager: CollisionManager
    //聊天款组件相关
    private lateinit var stage: Stage
    private lateinit var skin: Skin
    private lateinit var chatButton: TextButton
    private lateinit var chatDialog: ChatDialog

    //渲染碰撞形状
    //private val debugRenderer = ShapeRenderer()

    override fun show() {
        //地图大小和摄影机视口都是相对于游戏世界坐标
        mapLoader = MapLoader("tiled-map/PetMap.tmx")
        // 初始化摄影机和渲染地图
        cameraController = CameraController(mapLoader,150f)
        cameraController.applyViewport()
        mapRenderer = MapRenderer(mapLoader.map, cameraController.camera)//实例化地图渲染对象
        mapRenderer.setView()
        //初始化宠物实例
        pet = Pet(300f,600f,12f)
        batch = SpriteBatch()
        //设置摄影机位置以人物为中心
        cameraController.setCameraPosition(pet)
        //应用屏幕视口以绘制屏幕UI,确保后续基于该视口的绘制操作能够正确显示在屏幕上
        screenViewport.apply()
        // 显示按钮布局，相对于屏幕
        buttonGroup = ButtonGroup(screenWidth.toFloat(),screenHeight.toFloat())
        // 创建碰撞管理器
        collisionManager = CollisionManager(mapLoader)
        // 将碰撞管理器设置到宠物
        pet.setCollisionManager(collisionManager)

        stage = Stage(screenViewport)
        skin = Skin(Gdx.files.internal("uiskin.json"))
        val chineseFont = skin.getFont("chinese-font")
        val buttonStyle = TextButton.TextButtonStyle().apply {
            font = chineseFont
            fontColor = Color.WHITE
            up = skin.getDrawable("default-round")
            down = skin.getDrawable("default-round-down")
        }

        chatButton = TextButton("聊天", buttonStyle)
        chatButton.setSize(200f, 80f)
        chatButton.setPosition(20f, stage.viewport.worldHeight - chatButton.height - 100f)
        chatButton.addListener(object : ClickListener() {
            override fun clicked(event: InputEvent?, x: Float, y: Float) {
                chatDialog.isVisible = true
                chatDialog.setPosition(
                    (stage.viewport.worldWidth - chatDialog.width) / 2f,
                    (stage.viewport.worldHeight - chatDialog.height) / 2f
                )
                chatDialog.toFront()
            }
        })

        chatDialog = ChatDialog(stage, pet,chatService,historyRepo,analyzeEmotionService,skin).apply {
            setSizeBasedOnStage()
        }

        stage.addActor(chatButton)
        stage.addActor(chatDialog)

        Gdx.input.inputProcessor = InputMultiplexer(stage)
    }

    //输入处理 → 状态更新 → 视图更新 → 渲染
    override fun render(delta: Float) {
        //Gdx.gl.glEnable(GL20.GL_BLEND)
        //Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)

        // 1. 处理输入（获取触摸/按键状态）
        handleTouchInput(delta)  // 包含按钮和角色状态更新

        // 2. 更新游戏状态（按钮状态、角色状态、相机位置）
        buttonGroup.update(touchPos, Gdx.input.isTouched)// 更新方向键状态
        pet.updatePetMove(buttonGroup, delta)  // 根据方向键决定角色移动和动画状态更新
        cameraController.updateCamera(pet,delta)  // 相机根据角色新位置计算目标位置
        stage.act(delta)

        // 3. 渲染地图（依赖最新的相机视图）
        // 根据相机是否更新位置设置地图渲染的相机视图
        if (cameraController.camera.position.x != cameraController.lastCameraX
            || cameraController.camera.position.y != cameraController.lastCameraY) {//
            mapRenderer.setView()
            cameraController.lastCameraY = cameraController.camera.position.y
        }
        mapRenderer.render()  // 渲染地图

        //collisionManager.render(pet)

        // 4. 绘制游戏世界元素（角色）
        batch.begin()
        batch.projectionMatrix = cameraController.camera.combined
        pet.draw(batch)  // 角色绘制在地图之上
        batch.end()

        // 5. 绘制 UI 元素（移动、聊天按钮，独立于游戏世界坐标系）
        batch.begin()
        batch.projectionMatrix = screenViewport.camera.combined
        buttonGroup.draw(batch)  // 按钮绘制在最上层
        batch.end()
        stage.draw()
        //Gdx.gl.glDisable(GL20.GL_BLEND)
    }


    //触摸逻辑
    private fun handleTouchInput(delta: Float) {
        //检测屏幕是否当前触摸或者正在触摸
        if (Gdx.input.justTouched() || Gdx.input.isTouched) {
            //获取触摸点坐标，使用 screenViewport.unproject 将触摸点的坐标转换为屏幕坐标系中的坐标
            touchPos.set(Gdx.input.x.toFloat(), Gdx.input.y.toFloat())
            screenViewport.unproject(touchPos)
        } else {
            buttonGroup.update(touchPos, false) // 释放所有按钮
        }
    }

    override fun resize(width: Int, height: Int) {
        cameraController.viewport.update(width, height)
        stage.viewport.update(width, height, true)

        chatButton.setPosition(20f, stage.viewport.worldHeight - chatButton.height - 20f)
        chatDialog.setPosition(
            (stage.viewport.worldWidth - chatDialog.width) / 2f,
            (stage.viewport.worldHeight - chatDialog.height) / 2f
        )
        screenViewport.update(width, height,true)
    }

    override fun dispose() {
        mapRenderer.dispose()
        batch.dispose()
        pet.dispose()
        stage.dispose()
        skin.dispose()
        buttonGroup.dispose()
    }
}
